﻿using Autofac;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using WebSocketCore.Domain;
using WebSocketCore.Domain.Cfg;
using WebSocketCore.Domain.Impl;

namespace WebSocketCore.Cfg
{
    public static class WebSocketStartup
    {
        public static WebSocketOptions WebSocketOptions = new WebSocketOptions()
        {
            KeepAliveInterval = TimeSpan.FromSeconds(120),
            ReceiveBufferSize = 4 * 1024
        };
        public static IApplicationBuilder UseWebSocketConfigure(this IApplicationBuilder app)
        {
            app.Map("/ws", WebSocket);
            return app;
        }
        public static void WebSocket(IApplicationBuilder app)
        {
            app.Run(async context =>
            {
                if (context.WebSockets.IsWebSocketRequest)
                {
                    await Invoke(context, await context.WebSockets.AcceptWebSocketAsync());
                }
                else
                {
                    context.Response.StatusCode = 400;
                }
            });
        }
        private static async Task Invoke(HttpContext context, WebSocket webSocket)
        {
            IWebSocketInvoker invoker = Ioc.Container.Resolve< IWebSocketInvoker>();
            await invoker.InvokeAsync(context, webSocket);
        }
    }
}
